import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by codeczx on 2018/3/22.
 */
public class WebCrawler {

    private TrackingExecutor exec;

    WebCrawler(TrackingExecutor exec){
        this.exec = exec;
    }

    public void start() {
        for (int i = 0; i < 100; i++) {
            exec.execute(new CrawlerRunnable(i));
        }
    }

    public void stop(){
        List<Runnable> runnableList = exec.shutdownNow();
        System.out.println(runnableList.toString());
        try {
            if(exec.awaitTermination(10, TimeUnit.SECONDS)){
                runnableList.addAll(exec.getCanceledTask());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (Runnable runnable : runnableList) {
            System.out.println(runnable.getClass());
//            System.out.println("runnable-" + ((CrawlerRunnable) runnable).id);
        }
    }

    private class CrawlerRunnable implements Runnable {

        int id;

        CrawlerRunnable(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            try {
                System.out.println("runnable"+id);
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                System.out.println("runnable"+id+" interrupt");
                e.printStackTrace();
            }
        }
    }
}
